<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.username" placeholder="用户名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.phone" placeholder="电话" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.company" class="filter-item" clearable placeholder="所属商户">
        <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="listQuery.gender" placeholder="性别" clearable style="width: 110px" class="filter-item">
        <el-option v-for="item in sexOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 110px" class="filter-item">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
          <div>
            <span class="link-type" style="font-size: 5px;margin-left: 10px;" @click="handleUserRole(row.id)">重置密码</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="昵称" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="90px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status == 0? '禁用':'启用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="图标" width="90px" align="center">
        <template slot-scope="{row}">
          <img :src="row.icon" class="user-avatar">
        </template>
      </el-table-column>
      <el-table-column label="性别" width="90px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.gender | sexFilter">
            {{ row.gender == 1? '男':'女' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="积分" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.integration }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成长值" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.growth }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余抽奖次数" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.luckeyCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="历史积分数量" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.historyIntegration }}</span>
        </template>
      </el-table-column>
      <el-table-column label="来源" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.source }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商户" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.companyName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='1'" size="mini" type="success" @click="handleModifyStatus(row,'1')">
            启用
          </el-button>
          <el-button v-if="row.status!='0'" size="mini" @click="handleModifyStatus(row,'0')">
            禁用
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
          <div style="padding-top: 10px;">
            <span class="link-type" style="font-size: 5px;" @click="handleUserRole(row)">分配角色</span>
            <span class="link-type" style="margin-left: 5px;font-size: 5px;" @click="handleUserApp(row)">授权应用</span>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="temp.nickname" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择">
            <el-option v-for="item in statusNewOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="temp.gender" class="filter-item" placeholder="请选择">
            <el-option v-for="item in sexNewOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="temp.icon" />
        </el-form-item>
        <el-form-item label="商户" prop="company">
          <el-select v-model="temp.company" class="filter-item" clearable placeholder="请选择">
            <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogUserRoleVisbile" :title="userRoleTemp.title">
      <div style="width: 80%">
        <el-checkbox-group ref="roleGroup" v-model="roleIds" style="padding: 5px 15px;">
          <el-checkbox v-for="item in roleList" :label="item.id" style="width: 90px;">
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUserRoleVisbile = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveRoles()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogUserAppVisbile" :title="userAppTemp.title">
      <div style="width: 80%">
        <el-checkbox-group ref="appGroup" v-model="appIds" style="padding: 5px 15px;">
          <el-checkbox v-for="item in appList" :label="item.id" style="width: 90px;">
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUserAppVisbile = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveApps()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {userList, userRoleUpdate, userAppUpdate, userCreate, userUpdate, userDelete, userRoleList, userAppList, companyList} from '@/api/sys'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'sysUser',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success'
      }
      return statusMap[status]
    },
    sexFilter(status) {
      const statusMap = {
        1: 'error',
        2: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 15,
        gender: '',
        status: '',
        username: '',
        phone: '',
        company: '',
        sort: '+id'
      },
      sexOptions: [{ value:'', label:'性别-全部'}, { value:'1', label:'男'}, { value:'2', label:'女'}],
      statusOptions: [{ value:'', label:'状态-全部'}, { value:'0', label:'禁用'}, { value:'1', label:'启用'}],
      sexNewOptions: [{ value:'1', label:'男'}, { value:'2', label:'女'}],
      statusNewOptions: [{ value:'1', label:'启用'},{ value:'0', label:'禁用'}],
      temp: {
        id: undefined,
        status: '',
        gender: '',
        username: '',
        phone: '',
        icon: '',
        nickname: '',
        company: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      dialogUserRoleVisbile: false,
      dialogUserAppVisbile: false,
      rules: {
        username: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
        phone: [{ required: true, message: '请填写手机号', trigger: 'blur' }],
        company: [{ required: true, message: '请选择商户', trigger: 'blur' }]
      },
      userRoleTemp: {
        id: undefined,
        roles: [],
        title: ''
      },
      roleList: [],
      roleIds: [],
      userAppTemp: {
        id: undefined,
        apps: [],
        title: ''
      },
      appList: [],
      appIds: [],
      companyList: []
    }
  },
  created() {
    this.getList()

    this.companyListFun()
  },
  methods: {
    getList() {
      this.listLoading = true
      userList(this.listQuery).then(response => {
        this.list = response.data.content
        this.total = parseInt(response.data.totalElements)

        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      const tempData = {};
      tempData.status = status;
      tempData.id = row.id;
      userUpdate(tempData).then(() => {
        this.$notify({
          title: '提示',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    async companyListFun(){
      this.companyList = []
      await companyList({page: 1, limit: 10000, sort: '+id'}).then(response => {
        this.companyList = response.data.content
        this.companyList.unshift({id: '0', name: '无'})
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        status: '1',
        gender: '1',
        username: '',
        phone: '',
        icon: '',
        nickname: '',
        company: ''
      }
    },
    handleCreate() {
      this.resetTemp()

      this.companyListFun()

      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })

    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          userCreate(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.companyListFun()

      this.temp = Object.assign({}, row) // copy obj
      this.temp.status = row.status + ""
      this.temp.gender = row.gender + ""
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })

    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          userUpdate(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      const tempData = {};
      tempData.id = row.id;
      const that = this;
      this.$confirm('确认删除？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning'
      }).then(function(){
        userDelete(tempData).then(() => {
          that.$notify({
            title: '提示',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
          that.getList()
        })
      }).catch(function(){
        // console.log("取消成功！");
      })
    },
    handleUserRole(row) {
      this.userRoleTemp.title = '分配角色-当前用户['+row.username+']';
      this.userRoleTemp.id = row.id;
      userRoleList({id: row.id}).then(response => {
        this.roleList = response.data.roles;
        this.roleIds = response.data.userOwns;

        this.dialogUserRoleVisbile = true
      })
    },
    saveRoles(){
      this.userRoleTemp.roles = this.$refs.roleGroup.value
      userRoleUpdate(this.userRoleTemp).then(response => {
        this.$notify({
          title: '提示',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleUserApp(row) {
      this.userAppTemp.title = '授权应用-当前用户['+row.username+']';
      this.userAppTemp.id = row.id;
      userAppList({id: row.id}).then(response => {
        this.appList = response.data.apps;
        this.appIds = response.data.userOwns;

        this.dialogUserAppVisbile = true
      })
    },
    saveApps(){
      this.userAppTemp.apps = this.$refs.appGroup.value
      userAppUpdate(this.userAppTemp).then(response => {
        this.$notify({
          title: '提示',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style lang="scss" scoped>

  .user-avatar {
    cursor: pointer;
    width: 40px;
    height: 40px;
    border-radius: 10px;
  }

</style>
